﻿using Bnbjoy.Business.Abstract;
using Bnbjoy.Domain.Abstract;
using Bnbjoy.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace Bnbjoy.Business.Concrete
{
    public class MobileCaptchaService : IMobileCaptchaService
    {
        private IMobileCaptchaRepository _mobileCaptchaRepository;

        public MobileCaptchaService(IMobileCaptchaRepository mobileCaptchaRepository)
        {
            _mobileCaptchaRepository = mobileCaptchaRepository;
        }

        public async Task<bool> SendMobileCaptcha(string mobileNum)
        {
            try
            {
                Random random = new Random();
                String vCode = random.Next(10000, 1000000).ToString("D6"); //生成6位验证码

                ITopClient client = new DefaultTopClient(this.SmsServiceUrl, this.SmsServiceAppKey, this.SmsServiceAppSecret);
                AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
                req.Extend = "";
                req.SmsType = "normal";
                req.SmsFreeSignName = this.SmsSignName;
                req.SmsParam = "{code:'" + vCode + "'}";
                req.RecNum = mobileNum;
                req.SmsTemplateCode = this.SmsTemplate;

                var mobileCaptcha = new MobileCaptcha 
                {
                    MobileNumber = req.RecNum,
                    Code = vCode,
                    IssuedTime = DateTime.Now,
                    ExpiredTime = DateTime.Now.AddSeconds(60 * 10) //10分钟内有效
                };

                //数据插入成功后，才开始发送
                bool generateMobileCaptcha = await _mobileCaptchaRepository.Insert(mobileCaptcha);
                if (generateMobileCaptcha)
                {
                    AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req);
                }
                else 
                {
                    return false;
                }

                return true; 
            }
            catch (Exception ex) 
            {
                return false;
            }
        }

        public async Task<bool> RemoveMobileCaptcha(string mobileNum) 
        {
             var mobileCaptcha = await _mobileCaptchaRepository.FindByNumber(mobileNum);
             if (mobileCaptcha != null)
             {
                 return await _mobileCaptchaRepository.Delete(mobileCaptcha);
             }
             else 
             {
                 return false;
             }
        }

        public async Task<bool> VerifyMobileCaptcha(string mobileNum, string vCode) 
        {
            var mobileCaptcha = await _mobileCaptchaRepository.FindByNumber(mobileNum);
            if (mobileCaptcha != null)
            {
                if (mobileCaptcha.ExpiredTime > DateTime.Now)
                {
                    if (mobileCaptcha.Code == vCode)
                    {
                        //验证码未过期，且匹配上，删除记录，返回true
                        return true;
                    }
                    else 
                    {
                        return false; //如果未过期，但验证码不匹配，直接返回false
                    }
                }
                else
                {
                    //如果已过期，删除记录，直接返回false
                    await _mobileCaptchaRepository.Delete(mobileCaptcha); 
                    return false;
                }
            }
            else 
            {
                //没有该手机号的验证码记录，直接返回false
                return false;
            }
        }

        public void Dispose()
        {
        }

        private string SmsServiceUrl
        {
            get
            {
                return ConfigurationManager.AppSettings["SmsServiceUrl"] ?? "";
            }
        }

        private string SmsServiceAppKey
        {
            get
            {
                return ConfigurationManager.AppSettings["SmsServiceAppKey"] ?? "";
            }
        }

        private string SmsServiceAppSecret
        {
            get
            {
                return ConfigurationManager.AppSettings["SmsServiceAppSecret"].TrimEnd('/') ?? "";
            }
        }

        private string SmsSignName 
        {
            get 
            {
                return ConfigurationManager.AppSettings["SmsSignName"] ?? ""; 
            }
        }

        private string SmsTemplate 
        {
            get 
            {
                return ConfigurationManager.AppSettings["SmsTemplate"] ?? "";
            }
        }
    }
}
